package com.guet.niit.Login.controller.user;

import com.guet.niit.Login.pojo.Account;
import com.guet.niit.Login.pojo.User;
import com.guet.niit.Login.pojo.UserCar;
import com.guet.niit.Login.service.UserService;
import com.guet.niit.util.PhotoManage;
import com.guet.niit.util.UserBacktrack;
import com.sun.javafx.stage.StageHelper;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TextInputDialog;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

public class UserInfoFxController implements Initializable {

    public static UserInfoFxController userInfoFxController;

    @FXML
    ImageView backtrack;

    @FXML
    ImageView headPhoto;

    @FXML
    Text username;

    @FXML
    Text balance;

    @FXML
    Text phone;

    @FXML
    HBox car;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        userInfoFxController = this;
    }

    /**
     * 返回用户菜单
     * @param mouseEvent
     */
    public void backtrack(MouseEvent mouseEvent) {
        UserBacktrack.backtrack(UserInfoFxController.class);
    }

    /**
     * 读取个人信息
     */
    public void readUserInfo(User user){
        String newUsername = user.getUsername();
        //读取用户名
        username.setText(newUsername);
    }

    /**
     * 读取个人账户
     * @param account
     */
    public void readUserAccount(Account account){
        String newBalance = account.getBalance().toString();
        String newPhone = account.getPhone();
        //读取余额
        balance.setText(newBalance);
        //读取电话
        phone.setText(newPhone);
    }

    /**
     * 读取头像
     * @param newPhoto
     */
    public void readPhoto(String newPhoto){
        headPhoto.setImage(new Image(newPhoto));
    }

    /**
     * 读取个人车辆信息
     * @param mouseEvent
     */
    public void selectCar(MouseEvent mouseEvent) {
        //获取当前登录用户的id
        String name = Thread.currentThread().getName();
        long userId = Long.parseLong(name);
        //调用service层查询用户的车辆信息
        UserService userService = new UserService();
        List<UserCar> userCars = userService.selectUserCar(userId);

        //如果没有查询到车辆信息，则返回空界面
        if (userCars.size()>0){
            //引用fxml样式
            Parent load = null;
            try {
                load = FXMLLoader.load(getClass().getResource("/fxml/user/userCarList.fxml"));

            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取当前窗口，并将Scene更换为用户菜单的Scene
            ObservableList<Stage> stageList = StageHelper.getStages();
            stageList.get(0).setScene(new Scene(load));
            //读取个人车辆信息
            UserCarListFxController.userCarListFxController.readUserCarInfo(userCars);

        }else {
            //引用fxml样式
            Parent load = null;
            try {
                load = FXMLLoader.load(getClass().getResource("/fxml/user/nullUserCarList.fxml"));

            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取当前窗口，并将Scene更换为用户菜单的Scene
            ObservableList<Stage> stageList = StageHelper.getStages();
            stageList.get(0).setScene(new Scene(load));
        }
    }

    /**
     * 选择图片
     * @param mouseEvent
     */
    public void selectPhoto(MouseEvent mouseEvent) {
        FileChooser fileChooser = new FileChooser();
        //设置弹窗的样式
        Stage stage = new Stage();
        fileChooser.setTitle("选择图片");
        //获取当前使用的计算机用户名
        String computerUsername = System.getProperty("user.name");
        //设置默认的图片选择路径
        fileChooser.setInitialDirectory(new File("C:/Users/"+computerUsername+"/Pictures"));
        //设置可选择的文件类型
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("图片类型","*.jpg","*.png"),
                new FileChooser.ExtensionFilter("所有类型","*.*")
        );
        File file = fileChooser.showOpenDialog(stage);
        //选择图片后进行上传图片操作，否则关闭弹窗
        if (file!=null){
            //调用PhotoManage工具类上传图片，获取图片的源路径和图片名
            Map<String,String> photoProperties = PhotoManage.getPhotoProperties(file);
            Set<String> keys = photoProperties.keySet();
            //设置图片源路径和图片名
            String photoName = null;
            String fileAbsolutePath = null;
            for (String key : keys) {
                //获取图片源路径
                if (key.equals("fileAbsolutePath")){
                    fileAbsolutePath = photoProperties.get(key);
                }
                //获取图片名
                if (key.equals("photoName")){
                    photoName = photoProperties.get(key);
                }
            }
            //获取当前用户id
            String name = Thread.currentThread().getName();
            long userId = Long.parseLong(name);
            System.out.println(userId);
            //封装数据到实体类
            User user = new User(userId,photoName);
            //调用上传头像方法
            upload(user,fileAbsolutePath);
        }else {
            return;
        }
    }

    /**
     * 上传头像
     */
    public void upload(User user,String fileAbsolutePath){
        UserService userService = new UserService();
        //调用service层修改用户头像
        String status = userService.userUpload(user);
        //调用PhotoManage工具类下载图片，获取图片保存的路径
        String newPhoto = PhotoManage.downLoad(fileAbsolutePath,user.getPhoto());
        //若修改头像成功，则回显头像
        if (status=="success"){
            //回显图片
            headPhoto.setImage(new Image("file:"+newPhoto));
        }
    }

    /**
     * 修改用户名字
     * @param mouseEvent
     */
    public void changeUserName(MouseEvent mouseEvent) {
        TextInputDialog dialog = new TextInputDialog("");
        dialog.setTitle("用户名修改");
        dialog.setHeaderText("");
        dialog.setContentText("请输入新的用户名:");
        Optional<String> result = dialog.showAndWait();
        //用户点击确定
        if (result.isPresent()){
            //获取用户输入的用户名
            String newUserName = result.get();
            //获取当前登录用户的id
            String name = Thread.currentThread().getName();
            long userId = Long.parseLong(name);
            //调用service层修改用户名
            UserService userService = new UserService();
            User user = new User();
            user.setId(userId);
            user.setUsername(newUserName);
            userService.updateUserName(user);
            //查询用户信息
            User updateUserInfo = userService.selectUserInfo(userId);
            //回显号码
            String latestUserName = updateUserInfo.getUsername();
            username.setText(latestUserName);
        }
    }

    /**
     * 修改用户电话
     * @param mouseEvent
     */
    public void changePhone(MouseEvent mouseEvent) {
        TextInputDialog dialog = new TextInputDialog("");
        dialog.setTitle("电话修改");
        dialog.setHeaderText("");
        dialog.setContentText("请输入新的电话:");
        Optional<String> result = dialog.showAndWait();
        //用户点击确定
        if (result.isPresent()){
            //获取用户输入的号码
            String newPhone = result.get();
            //获取当前登录用户的id
            String name = Thread.currentThread().getName();
            long userId = Long.parseLong(name);
            //调用service层修改电话
            UserService userService = new UserService();
            Account account = new Account();
            account.setId(userId);
            account.setPhone(newPhone);
            userService.updatePhone(account);
            //查询账户
            Account updateAccount = userService.selectAccount(userId);
            //回显号码
            String latestPhone = updateAccount.getPhone();
            phone.setText(latestPhone);
        }
    }
}
